#coding=utf-8
import pycurl,StringIO
import urllib2 as request,urllib as parse,cookielib
import os,random,re,time
import json.encoder as json_encode,json.decoder as json_decode
import md5
class Api_connect:
        #API CONNECT QQ SOCKET
    __headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.9 Safari/534.30',\
        'Referer':'http://ui.ptlogin2.qq.com/cgi-bin/login?target=self&style=5&mibao_css=m_webqq&appid=1003903&enable_qlogin=0&no_verifyimg=1&s_url=http%3A%2F%2Fwebqq.qq.com%2Floginproxy.html&f_url=loginerroralert&strong_login=1&login_state=10&t=20110909003'\
    }
    __data = {
        'qq':0,
        'pswd':None,
        'verifycode':None,
        'cookiepath':None,
        'clientid':85421035,
        'psessionid':'',
        'ptwebqq':'',
        'vfwebqq':'',
        'skey':'',
        'rc':0,
        'send_num':74210001
    } #登陆以后存放数据
    __http = {} #http进程信息
    __version__ = '1.0'
    def __init__(self,mydata):
        self.mydata = mydata
        pass
    def __httpproess(self):
        #初始化模拟进程
        self.__http['cj'] = cookielib.MozillaCookieJar(self.__data['cookiepath'])
        self.__http['opener'] = request.build_opener(request.HTTPCookieProcessor(self.__http['cj']))
        pass
    def __httpproess2(self):

        pass
    def __urlopen2(self,url,method='GET',data={},savecookie=False,isimg=False):
        self.__http['opener'] = pycurl.Curl()
        #self.__http['opener'].setopt(pycurl.VERBOSE,1)
        #self.__http['opener'].setopt(pycurl.MAXREDIRS, 5)
        self.__http['opener'].setopt(pycurl.AUTOREFERER,1)
        if (method).upper() == 'POST':
            data = parse.urlencode(data)
            self.__http['opener'].setopt(pycurl.POST, True)
            self.__http['opener'].setopt(pycurl.POSTFIELDS, data)
        else:
            self.__http['opener'].setopt(pycurl.HTTPGET, True)
        self.__http['opener'].setopt(pycurl.CONNECTTIMEOUT, 60) #连接超时
        self.__http['opener'].setopt(pycurl.TIMEOUT, 300) #超时
        #self.__http['opener'].setopt(pycurl.FOLLOWLOCATION, True)
        if len(self.__headers) > 0:
            self.__http['opener'].setopt(pycurl.HTTPHEADER,['%s:%s'%(i,self.__headers[i]) for i in self.__headers])
        self.__http['opener'].setopt(pycurl.URL,str(url))
        if savecookie == True:
            self.__http['opener'].setopt(pycurl.COOKIEJAR, self.__data['cookiepath'])
        self.__http['opener'].setopt(pycurl.COOKIEFILE, self.__data['cookiepath'])
        self.__http['opener'].fp = StringIO.StringIO()
        self.__http['opener'].setopt(pycurl.WRITEFUNCTION, self.__http['opener'].fp.write)
        if isimg == True:
            self.__http['opener'].header = StringIO.StringIO()
            self.__http['opener'].setopt(pycurl.HEADERFUNCTION,self.__http['opener'].header.write)
        self.__http['opener'].perform()
        if isimg == True:
            strt = []
            strt.append(self.__http['opener'].fp.getvalue())
            strt.append(self.__http['opener'].header.getvalue())
        else:
            strt = (self.__http['opener'].fp.getvalue()).decode('utf-8')
        self.__http['opener'].close()
        return strt
    def __urlopen(self,url,method='GET',data={},savecookie=False,isimg=False):
        try:
            if (method).upper() == 'POST':
                data = parse.urlencode(data).encode('utf-8')
                self.__http['req'] = request.Request(url,data,self.__headers)
            else:
                self.__http['req'] = request.Request(url=url,headers=self.__headers)
            fp = self.__http['opener'].open(fullurl=self.__http['req'],timeout=120)
            try:
                if isimg == True:
                    str = []
                    str.append(fp.read())
                    str.append(fp.headers)
                else:
                    #['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', 'code', 'fileno', 'fp', 'getcode', 'geturl', 'headers', 'info', 'msg', 'next', 'read', 'readline', 'readlines', 'url']
                    str = fp.read().decode('utf-8')
            except UnicodeDecodeError:
                str = fp.read()
            if savecookie == True:
                self.__http['cj'].save(ignore_discard=True,ignore_expires=True)
            fp.close()
            return str
        except Exception as e:
            print >> self.mydata.get('log','debug'),e
            return '{}'
    def __getcookies(self,name):
        fp = open(self.__data['cookiepath'])
        fp.seek(130) #138
        for read in fp.readlines():
            str = read.split(name)
            if len(str) == 2:
                fp.close()
                return str[1].strip()
        fp.close()
        return None
    def getverifycode(self):
        #验证码
        urlv = 'http://ptlogin2.qq.com/check?uin=%s&appid=1003903&r=%s'% (self.__data['qq'],random.Random().random())
        str = self.__urlopen(url = urlv, savecookie=True)
        self.__data['verifycode'] = re.findall(r'\d|(?<=\')[a-zA-Z0-9\!]{4}',str)
        return self.__data['verifycode']
    def request_login(self):
        #第一次get登陆
        pswd = md5.QQmd5().md5(self.__data['pswd'],self.__data['verifycode'][1])
        urlv = 'http://ptlogin2.qq.com/login?u='+('%s' %  self.__data['qq']) +'&' +  'p=' + ('%s' % pswd) +  '&verifycode='+ ('%s' % self.__data['verifycode'][1]) +'&remember_uin=1&aid=1003903' +  "&u1=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html%3Fstrong%3Dtrue" +  '&h=1&ptredirect=0&ptlang=2052&from_ui=1&pttype=1&dumy=&fp=loginerroralert'
        return self.__urlopen(url = urlv,savecookie=True)
    def request_login2(self):
        #第二次post登陆
        self.__headers.update({'Referer':'http://d.web2.qq.com/proxy.html?v=20110331002&callback=2'})
        a = {'status':'online','ptwebqq':self.__getcookies('ptwebqq'),'passwd_sig':'','clientid':self.__data['clientid'],'psessionid':'null','tid':'%s'%self.__data['clientid']}
        array = {'r':json_encode.JSONEncoder().encode(a),'clientid':self.__data['clientid'],'psessionid':'null'}
        url = 'http://d.web2.qq.com/channel/login2'
        str = self.__urlopen(url,'POST',array)
        self.__data['login_info'] = json_decode.JSONDecoder().decode(str)
        if(self.__data['login_info'].has_key('result')):
            self.__data['psessionid'] = self.__data['login_info']['result']['psessionid']
            self.__data['vfwebqq'] = self.__data['login_info']['result']['vfwebqq']
        return self.__data['login_info']
    def poll2_(self):
        #不知道干嘛的，一分钟连接一次，属于长连接，接收消息
        self.__headers.update({'Referer':'http://d.web2.qq.com/proxy.html?v=20110331002&callback=2'})
        urlv = 'http://d.web2.qq.com/channel/poll2'
        a = {'clientid':self.__data['clientid'],'psessionid':self.__data['psessionid'],'key':0,'ids':[]}
        array = {'r':json_encode.JSONEncoder().encode(a),'clientid':self.__data['clientid'],'psessionid':self.__data['psessionid']}
        self.__poll2 = self.__urlopen(url = urlv,method='POST',data = array)
        return json_decode.JSONDecoder().decode(self.__poll2)
    def get_msg_tip_(self):
        #也不知道是什么，反正一直请求
        self.__headers.update({'Referer':'http://webqq.qq.com/'})
        self.__data['rc'] += 1
        num = 100 + self.__data['rc']
        t = '%s' % '%d' % time.time() + '%s' % num
        urlv = 'http://webqq.qq.com/web2/get_msg_tip?uin=&tp=1&id=0&retype=1&rc='+'%s'% self.__data['rc'] +'&lv=3&t=' + t
        return json_decode.JSONDecoder().decode(self.__urlopen(urlv))
    def get_friend_info2(self):
        #@url:http://s.web2.qq.com/api/get_friend_info2?tuin=self.__qq&verifysession=&code=&vfwebqq=self.__vfwebqq
        self.__headers.update({'Referer':'http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=2'})
        url = 'http://s.web2.qq.com/api/get_friend_info2?tuin=%s'% self.__data['qq'] + '&verifysession=&code=&vfwebqq=%s' % self.__data['vfwebqq'] + '&t=%s' % '%d' % time.time() + '100'
        return json_decode.JSONDecoder().decode(self.__urlopen(url))
    def get_user_friends2(self):
        #@url:http://s.web2.qq.com/api/get_user_friends2
        self.__headers.update({'Referer':'http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=2'})
        url = 'http://s.web2.qq.com/api/get_user_friends2'
        a = {'h':'hello','vfwebqq':self.__data['vfwebqq']}
        array = {'r':json_encode.JSONEncoder().encode(a)}
        return json_decode.JSONDecoder().decode(self.__urlopen(url,'POST',array))
        #print(str)
    def get_group_name_list_mask2(self):
        #@url:http://s.web2.qq.com/api/get_group_name_list_mask2
        self.__headers.update({'Referer':'http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=2'})
        url = 'http://s.web2.qq.com/api/get_group_name_list_mask2'
        a = {'vfwebqq':self.__data['vfwebqq']}
        array = {'r':json_encode.JSONEncoder().encode(a)}
        return json_decode.JSONDecoder().decode(self.__urlopen(url,'POST',array))
        #print(str)
    def get_online_buddies2(self):
        #@url:http://d.web2.qq.com/channel/get_online_buddies2?clientid=3869990&psessionid=836d6&t=1319807070834
        self.__headers.update({'Referer':'http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=2'})
        url = 'http://d.web2.qq.com/channel/get_online_buddies2?clientid=%s'%self.__data['clientid']+'&psessionid=%s'%self.__data['psessionid']+'&t=%s' % '%d' % time.time() + '100'
        return json_decode.JSONDecoder().decode(self.__urlopen(url))
    def get_recent_list2(self):
        #@url:http://d.web2.qq.com/channel/get_recent_list2
        self.__headers.update({'Referer':'http://d.web2.qq.com/proxy.html?v=20110331002&callback=2'})
        url = 'http://d.web2.qq.com/channel/get_recent_list2'
        a = {'vfwebqq':self.__data['vfwebqq'],'clientid':self.__data['clientid'],'psessionid':self.__data['psessionid']}
        array = {'r':json_encode.JSONEncoder().encode(a),'clientid':self.__data['clientid'],'psessionid':self.__data['psessionid']}
        return json_decode.JSONDecoder().decode(self.__urlopen(url,'POST',array))
    def get_nick(self,uin):
        #@url:http://s.web2.qq.com/api/get_single_long_nick2?tuin=1014242230&vfwebqq=c3a50d3e4de85ef3&t=1320654418458
        self.__headers.update({'Referer':'http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=2'})
        self.__data['rc'] += 1
        num = 100 + self.__data['rc']
        t = '%s' % '%d' % time.time() + '%s' % num
        url='http://s.web2.qq.com/api/get_single_long_nick2?tuin=%s'%uin + '&vfwebqq=%s'%self.__data['vfwebqq']+'&t=%s'% t
        return json_decode.JSONDecoder().decode(self.__urlopen(url))
    def send_message(self,uid,msg):
        '''
            @url:http://d.web2.qq.com/channel/send_buddy_msg2
            r:{"to":3023379661,"face":180,"content":"[\"哈哈\",\"\\n【提示：此用户正在使用WebQQ：http://webqq.qq.com/】\",[\"font\",               {\"name\":\"宋体\",\"size\":\"10\",\"style\":[0,0,0],\"color\":\"000000\"}]]","msg_id":31330001,"clientid":"76133590",                    "psessionid":"s"}
                clientid:76133590
                psessionid:s

            Referer:http://d.web2.qq.com/proxy.html?v=20110331002&callback=2
            {"retcode":0,"result":"ok"}
        '''
        self.__data['send_num'] +=1
        msg = u"[\""+ msg +u"\",[\"font\",{\"name\":\""+u'宋体'+u"\",\"size\":\"10\",\"style\":[0,0,0],\"color\":\"000000\"}]]"
        self.__headers.update({'Referer':'http://d.web2.qq.com/proxy.html?v=20110331002&callback=2'});
        url = 'http://d.web2.qq.com/channel/send_buddy_msg2'
        a = {'to':uid,'face':180,'content':msg,'msg_id':self.__data['send_num'],'clientid':self.__data['clientid'],'psessionid':self.__data['psessionid']}
        array = {'r':json_encode.JSONEncoder().encode(a),'clientid':self.__data['clientid'],'psessionid':self.__data['psessionid']}
        return json_decode.JSONDecoder().decode(self.__urlopen(url,'POST',array))
    def send_group_message(self,gid,msg):
        '''
            @url:http://d.web2.qq.com/channel/send_qun_msg2
            r:{"group_uin":1132101900,"content":"[\"哈哈哈，测试\",\"\\n【提示：此用户正在使用WebQQ：http://webqq.qq.com/】\",[\"font\",           {\"name\":\"宋体\",\"size\":\"10\",\"style\":[0,0,0],\"color\":\"000000\"}]]","msg_id":31330002,"clientid":"76133590",
            "psessionid":"a"}
            clientid:76133590
            psessionid:a

            Referer:http://d.web2.qq.com/proxy.html?v=20110331002&callback=2

            {"retcode":0,"result":"ok"}
        '''
        self.__data['send_num'] +=1
        msg = u"[\""+ msg +u"\",[\"font\",{\"name\":\""+u'宋体'+u"\",\"size\":\"10\",\"style\":[0,0,0],\"color\":\"000000\"}]]"
        self.__headers.update({'Referer':'http://d.web2.qq.com/proxy.html?v=20110331002&callback=2'});
        url = 'http://d.web2.qq.com/channel/send_qun_msg2'
        a = {'group_uin':gid,'content':msg,'msg_id':self.__data['send_num'],'clientid':self.__data['clientid'],'psessionid':self.__data['psessionid']}
        array = {'r':json_encode.JSONEncoder().encode(a),'clientid':self.__data['clientid'],'psessionid':self.__data['psessionid']}
        return json_decode.JSONDecoder().decode(self.__urlopen(url,'POST',array))
    def get_group_info_ext2(self,tuin):
        #@url:http://s.web2.qq.com/api/get_group_info_ext2?gcode=3829192369&vfwebqq=01088b4&t=1321433055397
        self.__data['rc'] += 1
        num = 100 + self.__data['rc']
        t = '%s' % '%d' % time.time() + '%s' % num
        url = 'http://s.web2.qq.com/api/get_group_info_ext2?gcode=%s'%tuin+'&vfwebqq=%s'%self.__data['vfwebqq']+'&t=%s'%t
        return json_decode.JSONDecoder().decode(self.__urlopen(url))
    def get_friend_uin2(self,tuin,type=4):
        #@url:http://s.web2.qq.com/api/get_friend_uin2?tuin=3829192369&verifysession=&type=4&code=&vfwebqq=0102567&t=1321433563257 #群
        #@url:http://s.web2.qq.com/api/get_friend_uin2?tuin=1993816635&verifysession=&type=1&code=&vfwebqq=0102567&t=1321433748003 #qq
        self.__data['rc'] += 1
        num = 100 + self.__data['rc']
        t = '%s' % '%d' % time.time() + '%s' % num
        url = 'http://s.web2.qq.com/api/get_friend_uin2?tuin=%s'%tuin+'&verifysession=&type=%s'%type+'&code=&vfwebqq=%s'%self.__data['vfwebqq']+'&t=%s'%t
        return json_decode.JSONDecoder().decode(self.__urlopen(url))
    def img(self):
        #@url:http://captcha.qq.com/getimage?aid=1003903&r=0.47697025584056973&uin=644826377&vc_type=885f285fb4b0873d3a3ca4353fd230ab8b1fee74e89c0137
        #@Referer:http://ui.ptlogin2.qq.com/cgi-bin/login?target=self&style=5&mibao_css=m_webqq&appid=1003903&enable_qlogin=0&no_verifyimg=1&s_url=http%3A%2F%2Fwebqq.qq.com%2Floginproxy.html&f_url=loginerroralert&strong_login=1&login_state=10&t=20111028001
        #Set-Cookie:verifysession=h00c0afd04067a375d2ea0bff4b493c582ef6a2d5bf0a074f5aa730441211a7b88f052cb66232e1da792b1591c8bc00b333; PATH=/; DOMAIN=qq.com;
        urlv = 'http://captcha.qq.com/getimage?aid=1003903&r=0.47697025584056973&uin=%s'% self.__data['verifycode'] +'&vc_type=885f285fb4b0873d3a3ca4353fd230ab8b1fee74e89c0137'
        return self.__urlopen(url = urlv,method='GET',savecookie=True)
    def getface(self,uin,type=1):
        #@url:http://face5.qun.qq.com/cgi/svr/face/getface?cache=0&type=1&fid=0&uin=2375683774&vfwebqq=f703daba9a32c495db13d476d981214e9d6f4cd454dd1010a49147c4621a469f3dfa3b8998b5d5fb
        urlv = 'http://face%s'%random.randint(1,9)+'.qun.qq.com/cgi/svr/face/getface?cache=0&type=%s'%type+'&fid=0&uin=%s'%uin+'&vfwebqq=%s'%self.__data['vfwebqq']
        return self.__urlopen(urlv,isimg=True)
    def Login(self,qq,passwd):
        self.__data['qq'] = '%s'%qq
        self.__data['pswd'] = '%s'%passwd
        self.mkqqdir(self.__data['qq'])
        self.__data['cookiepath'] = './data/tw/{0}/{1}'.format(self.__data['qq'],'session')
        self.__httpproess()
    def setverifycode(self,value):
        self.__data['verifycode'] = '%s'%value
    def get_cface2(self,uin,msgid,imgid):
        self.__headers.update({'Referer':'http://webqq.qq.com/'})
        url = "http://d.web2.qq.com/channel/get_cface2?lcid={0}&guid={1}&to={2}&count=5&time=1&clientid={3}&psessionid={4}".format(str(msgid),str(imgid),str(uin),self.__data['clientid'],self.__data['psessionid'])
        return self.__urlopen(url,isimg=True)
        pass
    def file1(self):
        pass
    def mkqqdir(self,qq):
        dir = './data/tw/{0}'.format(qq)
        if os.path.exists(dir) == False:
            os.mkdir(dir)
            os.mkdir('{0}/temp'.format(dir))
